import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from '../utils/axios'

interface ResourceImage {
  id: number
  imageUrl: string
}

interface UserInfo {
  id: number
  username: string
}

interface Resource {
  id: number
  name: string
  description: string
  location: string
  status: number
  viewCount: number
  borrowCount: number
  userInfo: UserInfo
  resourceImageInfo?: ResourceImage[]
}

interface ResourcePubDTO {
  name: string
  description: string
  location: string
  categoryId: number
}

export const useResourceStore = defineStore('resource', () => {
  const resources = ref<Resource[]>([])
  const currentResource = ref<Resource | null>(null)

  const getResources = async (params: any) => {
    try {
      const response = await axios.get('/user/resource/list', { params })
      resources.value = response.data.data.records
      return response.data.data
    } catch (error) {
      console.error('获取资源列表失败:', error)
      return null
    }
  }

  const getResourceDetail = async (id: number) => {
    try {
      const response = await axios.get(`/user/resource/detail/${id}`)
      currentResource.value = response.data.data
      return response.data.data
    } catch (error) {
      console.error('获取资源详情失败:', error)
      return null
    }
  }

  const publishResource = async (resourceData: ResourcePubDTO, files: File[]) => {
    try {
      const formData = new FormData()
      formData.append('resourcePubDTO', JSON.stringify(resourceData))
      files.forEach(file => {
        formData.append('files', file)
      })
      await axios.post('/user/resource/pub', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      return true
    } catch (error) {
      console.error('发布资源失败:', error)
      return false
    }
  }

  return {
    resources,
    currentResource,
    getResources,
    getResourceDetail,
    publishResource
  }
}) 